<?php


namespace App\HttpController\Api;


use App\Model\Finance\ErrDec;
use App\Model\Token;
use App\Utility\Pool\RedisPool;
use App\Utility\ReverseProxyTools;
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\Http\AbstractInterface\Controller;
use Firebase\JWT\JWT;


class Base extends Controller
{

    protected function onRequest(?string $action): ?bool
    {

        if ($action == 'favicon') {
            var_dump($this->request()->getMethod());
            return false;
        }
        if ($this->request()->getMethod() == 'OPTIONS') {
            return false;
        }
        if (parent::onRequest($action)) {
            $token = new Token();
            //判断有没过期
            if (!$this->request()->hasHeader($token::TOKEN_HEADER)) {
                //$this->response()->redirect(BaseURL::LOGIN_URL);
                $this->fail(ErrDec::TOKEN_EXP);
                return false;
            }
            $token_str = $this->request()->getHeader($token::TOKEN_HEADER)[0];
            try {
                $deocde = JWT::decode($token_str, $token::JWTKEY, array('HS256'));

                //取缓存看有没对应有TOKEN
                $redis = RedisPool::defer();
                $uid = $redis->get($token_str);
                if ($uid != $deocde->uid) {
                    $this->fail(ErrDec::TOKEN_EXP);
                    return false;
                }


                ContextManager::getInstance()->set('user_id', $deocde->uid);
                //IP
                $ip = ReverseProxyTools::checkCurrentClientIP($this->request());
                ContextManager::getInstance()->set('client_ip', $ip);

                return true;
            } catch (\Exception $e) {
                $this->fail(ErrDec::TOKEN_EXP);
                return false;
            }
        }
        $this->fail(ErrDec::TOKEN_EXP);
        return false;

    }


    function index()
    {
        // TODO: Implement index() method.
        $this->actionNotFound('index');
    }

    protected function writeJson($statusCode = 200, $msg = null, $result = null)
    {
        if (!$this->response()->isEndResponse()) {
            $data = array(
                "code" => $statusCode,
                "data" => $result,
                "msg" => $msg
            );
            $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
            $this->response()->withStatus($statusCode);

            return true;
        } else {

            return false;
        }
    }

    protected function success($result)
    {
        $this->writeJson(200, 'SUCCESS', $result);

    }

    protected function fail($result)
    {
        $this->writeJson($result[0], $result[1]);
    }
}